package managedbean.Production;

import entity.Product;
import entity.ProductionBatch;
import entity.ProductionSchedule;
import entity.ProductionScheduleDay;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import managedbean.UserSessionManagerBean;
import session.stateless.LogSessionBeanLocal;
import session.stateless.ProductSessionBeanLocal;
import session.stateless.ProductionBatchSessionBeanLocal;
import session.stateless.ProductionScheduleSessionBeanLocal;

@ManagedBean(name = "productionBatchManagerBean")
@RequestScoped
public class ProductionBatchManagerBean implements Serializable {

    @EJB
    private ProductSessionBeanLocal productSessionBeanLocal;
    @EJB
    private ProductionScheduleSessionBeanLocal productionScheduleSessionBeanLocal;
    @EJB
    private ProductionBatchSessionBeanLocal productionBatchSessionBeanLocal;
    @EJB
    private LogSessionBeanLocal logSessionBeanLocal;
    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    private Boolean lock = false;
    private String loadAddProductionBatch;
    private String loadSearchProductionBatch;
    private String loadUpdateProductionBatch;
    private ProductionBatch productionBatch;
    private ArrayList<ProductionSchedule> productionSchedules = new ArrayList<ProductionSchedule>();
    private ArrayList<ProductionBatch> productionBatches = new ArrayList<ProductionBatch>();
    private Date date;
    private Date minDate;
    private String remark;
    private Integer quantity = 0;
    private String code;
    private ArrayList<Integer> lineNumbers = new ArrayList<Integer>();
    private Integer lineNumber;
    private ArrayList<Product> products = new ArrayList<Product>();
    private DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
    private String type;

    public String getLoadAddProductionBatch() {

        products = new ArrayList(productSessionBeanLocal.getProducts());

        if (userSessionManagerBean.getSelectedItem() != null) {
            try {
                lock = true;
                productionBatches = (ArrayList<ProductionBatch>) userSessionManagerBean.getSelectedItem();
                ArrayList<String> parameters = (ArrayList<String>) userSessionManagerBean.getParameters();
                Calendar cal = Calendar.getInstance();
                cal.set(Integer.parseInt(parameters.get(2)), Integer.parseInt(parameters.get(1)) - 1, Integer.parseInt(parameters.get(0)));
                date = cal.getTime();
                lineNumber = Integer.parseInt(parameters.get(3));
            } catch (Exception exception) {
                userSessionManagerBean.setSelectedItem(null);
                try {

                    FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                            + userSessionManagerBean.getServerName() + ":"
                            + userSessionManagerBean.getServerPort()
                            + "/MerlionERP-war/Web_Production/addProductionBatch.xhtml");
                } catch (Exception ex) {
                }
            }

        } else {

            minDate = Calendar.getInstance().getTime();
            String dateOfFc = df.format(minDate);
            String str[] = dateOfFc.split("-");

            productionSchedules = productionScheduleSessionBeanLocal.getProductionSchedules(Integer.parseInt(str[1]), Integer.parseInt(str[2]));
            for (ProductionSchedule ps : productionSchedules) {
                lineNumbers.add(ps.getLineNumber());
            }
            HashSet hs = new HashSet(lineNumbers);
            lineNumbers.clear();
            lineNumbers.addAll(hs);
        }



        return null;
    }

    public String getLoadSearchProductionBatch() {
        userSessionManagerBean.setSelectedItem(null);
        productionBatches = productionBatchSessionBeanLocal.getProductionBatches(false);
        return null;
    }

    public String getLoadUpdateProductionBatch() {

        try {
        } catch (Exception exception) {
            try {

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/searchProductionBatch.xhtml");
            } catch (Exception ex) {
            }
        }


        return null;
    }

    //<editor-fold defaultstate="collapsed" desc="Customer attributes. Click on the + sign on the left to edit the code.">
    public ProductionBatchManagerBean() {
    }

    /**
     * @return the productSessionBeanLocal
     */
    public ProductSessionBeanLocal getProductSessionBeanLocal() {
        return productSessionBeanLocal;
    }

    /**
     * @param productSessionBeanLocal the productSessionBeanLocal to set
     */
    public void setProductSessionBeanLocal(ProductSessionBeanLocal productSessionBeanLocal) {
        this.productSessionBeanLocal = productSessionBeanLocal;
    }

    /**
     * @return the userSessionManagerBean
     */
    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    /**
     * @param userSessionManagerBean the userSessionManagerBean to set
     */
    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    /**
     * @param loadAddProductionBatch the loadAddProductionBatch to set
     */
    public void setLoadAddProductionBatch(String loadAddProductionBatch) {
        this.loadAddProductionBatch = loadAddProductionBatch;
    }

    /**
     * @return the productionBatch
     */
    public ProductionBatch getProductionBatch() {
        return productionBatch;
    }

    /**
     * @param productionBatch the productionBatch to set
     */
    public void setProductionBatch(ProductionBatch productionBatch) {
        this.productionBatch = productionBatch;
    }

    /**
     * @return the productionBatches
     */
    public ArrayList<ProductionBatch> getProductionBatches() {
        return productionBatches;
    }

    /**
     * @param productionBatches the productionBatches to set
     */
    public void setProductionBatches(ArrayList<ProductionBatch> productionBatches) {
        this.productionBatches = productionBatches;
    }

    /**
     * @return the date
     */
    public Date getDate() {
        return date;
    }

    /**
     * @param date the date to set
     */
    public void setDate(Date date) {
        this.date = date;
    }

    /**
     * @return the minDate
     */
    public Date getMinDate() {
        return minDate;
    }

    /**
     * @param minDate the minDate to set
     */
    public void setMinDate(Date minDate) {
        this.minDate = minDate;
    }

    /**
     * @return the quantity
     */
    public Integer getQuantity() {
        return quantity;
    }

    /**
     * @param quantity the quantity to set
     */
    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    /**
     * @return the code
     */
    public String getCode() {
        return code;
    }

    /**
     * @param code the code to set
     */
    public void setCode(String code) {
        this.code = code;
    }

    /**
     * @return the lineNumber
     */
    public Integer getLineNumber() {
        return lineNumber;
    }

    /**
     * @param lineNumber the lineNumber to set
     */
    public void setLineNumber(Integer lineNumber) {
        this.lineNumber = lineNumber;
    }

    /**
     * @return the products
     */
    public ArrayList<Product> getProducts() {
        return products;
    }

    /**
     * @param products the products to set
     */
    public void setProducts(ArrayList<Product> products) {
        this.setProducts(products);
    }

    /**
     * @return the lineNumbers
     */
    public ArrayList<Integer> getLineNumbers() {
        return lineNumbers;
    }

    /**
     * @param lineNumbers the lineNumbers to set
     */
    public void setLineNumbers(ArrayList<Integer> lineNumbers) {
        this.lineNumbers = lineNumbers;
    }

    /**
     * @return the remark
     */
    public String getRemark() {
        return remark;
    }

    /**
     * @param remark the remark to set
     */
    public void setRemark(String remark) {
        this.remark = remark;
    }

    /**
     * @return the lock
     */
    public Boolean getLock() {
        return lock;
    }

    /**
     * @param lock the lock to set
     */
    public void setLock(Boolean lock) {
        this.lock = lock;
    }

    /**
     * @return the type
     */
    public String getType() {
        return type;
    }

    /**
     * @param type the type to set
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * @param loadSearchProductionBatch the loadSearchProductionBatch to set
     */
    public void setLoadSearchProductionBatch(String loadSearchProductionBatch) {
        this.loadSearchProductionBatch = loadSearchProductionBatch;
    }

    /**
     * @param loadUpdateProductionBatch the loadUpdateProductionBatch to set
     */
    public void setLoadUpdateProductionBatch(String loadUpdateProductionBatch) {
        this.loadUpdateProductionBatch = loadUpdateProductionBatch;
    }

    //</editor-fold>
    public void done(ActionEvent event) {
        String day = "";
        if (productionBatches != null) {

            for (ProductionBatch pb : productionBatches) {
                day = "";
                productionBatchSessionBeanLocal.addProductionBatch(pb.getQuantity(), pb.getRemark(), userSessionManagerBean.getUserId(), pb.getProduct().getCode(), pb.getProductionScheduleDay().getId());
                productionScheduleSessionBeanLocal.updateProductionScheduleDay(pb.getProductionScheduleDay().getId(), pb.getProductionScheduleDay().getQuantity());
                day = pb.getProductionScheduleDay().getCurrentDay().toString();
            }

            date = Calendar.getInstance().getTime();
            String dateOfFc = df.format(date);
            String str[] = dateOfFc.split("-");
            day += "/" + str[1] + "/" + str[2];


            ArrayList<String> al = new ArrayList<String>();
            al.add("Production batch successfully created");
            al.add("You have successfully created the a production batch for:" + day + ".");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_Production/addProductionBatch.xhtml");
            userSessionManagerBean.setSelectedItem(al);
            logSessionBeanLocal.addLog("Create production batch", "Production batch created  Day/Month/Year: " + day, "addProductionBatch.xhtml", userSessionManagerBean.getUserId());

            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/success.xhtml");
            } catch (Exception ex) {
            }


        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "No record found.", ""));

        }
    }

    public void add(ActionEvent event) {


        Product product = productSessionBeanLocal.getProduct(code);
        ProductionScheduleDay productionScheduleDay = null;

        String dateOfFc = df.format(date);
        String str[] = dateOfFc.split("-");

        for (ProductionSchedule ps : productionSchedules) {
            for (ProductionScheduleDay psd : ps.getProductionScheduleDays()) {
                if (psd.getCurrentDay().compareTo(Integer.parseInt(str[0])) == 0 && ps.getLineNumber().compareTo(lineNumber) == 0 && psd.getType().compareTo(type) == 0) {
                    productionScheduleDay = psd;
                }

            }
        }

        if (quantity > 0 && productionScheduleDay != null) {
            ProductionBatch pb = new ProductionBatch(null, quantity, 0, remark, null, null, product, productionScheduleDay);
            productionBatches.add(pb);


            try {

                userSessionManagerBean.setSelectedItem(productionBatches);
                ArrayList<String> parameters = new ArrayList<String>();
                parameters.add(str[0]);
                parameters.add(str[1]);
                parameters.add(str[2]);
                parameters.add(lineNumber.toString());
                userSessionManagerBean.setParameters(parameters);


                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/Web_Production/addProductionBatch.xhtml");
            } catch (Exception ex) {
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, 
                    "Product not scheduled for the selected production day. Please refer to calendar.", ""));
        }

    }

    public void selectProductionBatch(ActionEvent event) {
        if (productionBatch != null) {
            try {
                userSessionManagerBean.setSelectedItem(productionBatch);
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/searchWarehouseZones.xhtml?request=searchProductionBatch");
            } catch (Exception ex) {
            }

        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a production batch before continue.", ""));
        }

    }
}
